package mr.ali.videoapp.portal.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import org.json.JSONObject;

@RestController
@Slf4j
public class Phone {

    private static final String APP_ID = "wx6c0d4bf9d99cc8b3";
    private static final String APP_SECRET = "80932086f4060e5558a79c4c40888930";
    private static final String GET_VERIFY_INFO_URL = "https://api.weixin.qq.com/donut/code2verifyinfo";

//    @GetMapping("/getSession")
    public JSONObject getVerify(String code) throws Exception {
        log.info("前段获取的code: {}", code);
        if (code == null || code.isEmpty()) {
            throw new IllegalArgumentException("Invalid code");
        }

        // 构建请求URL
        String requestUrl = GET_VERIFY_INFO_URL + "?appid=" + URLEncoder.encode(APP_ID, "UTF-8") +
                "&secret=" + URLEncoder.encode(APP_SECRET, "UTF-8") +
                "&js_code=" + URLEncoder.encode(code, "UTF-8") +
                "&grant_type=authorization_code";
        log.info("请求微信服务器获取用户信息的URL: {}", requestUrl);
        URL url = new URL(requestUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");

        // 检查HTTP响应码
        int responseCode = conn.getResponseCode();
        log.info("微信服务器响应码: {}", responseCode);
        if (responseCode != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + responseCode);
        }

        // 读取响应内容
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();
log.info("微信服务器响应内容response: {}", response);
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // 解析JSON响应
        JSONObject jsonResponse = new JSONObject(response.toString());
        log.info("微信服务器响应内容response.toString(): {}", jsonResponse);
        if (jsonResponse.has("errcode")) {
            throw new RuntimeException("Error from WeChat API: " + jsonResponse.getString("errmsg"));
        }

        return jsonResponse; // 返回包含用户信息的JSONObject
    }

        private static final String GET_VERIFY_INFO = "https://api.weixin.qq.com/sns/jscode2session"; // 更新为正确的接口

//        @GetMapping("/getSessionInfo")
        public JSONObject getVerifyInfo(String code) throws Exception {
            log.info("前端获取的code: {}", code);
            if (code == null || code.isEmpty()) {
                throw new IllegalArgumentException("Invalid code");
            }

            // 使用URLEncoder对参数进行编码
            String requestUrl = GET_VERIFY_INFO + "?appid=" + URLEncoder.encode(APP_ID, "UTF-8") +
                    "&secret=" + URLEncoder.encode(APP_SECRET, "UTF-8") +
                    "&js_code=" + URLEncoder.encode(code, "UTF-8") +
                    "&grant_type=authorization_code";

            log.info("请求微信服务器获取用户信息的URL: {}", requestUrl);
            URL url = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

            // 检查HTTP响应码
            int responseCode = conn.getResponseCode();
            log.info("微信服务器响应码: {}", responseCode);
            if (responseCode != 200) {
                throw new RuntimeException("Failed : HTTP error code : " + responseCode);
            }

            // 读取响应内容
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 日志记录响应内容
            log.info("微信服务器响应内容response.toString(): {}", response);

            // 解析JSON响应
            JSONObject jsonResponse = new JSONObject(response.toString());
            if (jsonResponse.has("errcode")) {
                throw new RuntimeException("Error from WeChat API: " + jsonResponse.getString("errmsg"));
            }
            return jsonResponse; // 返回包含用户信息的JSONObject
        }
    }
